package com.ruima.study.jdk21.jdk19.demo1;

import java.time.Duration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

/**
 * <p>
 * <p></p>
 * <p>
 * <p>Copyright (c) 2024/11/13 11:26, 科大讯飞 All Rights Reserve</p>
 *
 * @author ruima6
 * @version [V1.0]
 */
public class VirtualDemo {
    public static void main(String[] args) {
        oldThread();
        virtualThread();
    }

    private static void virtualThread() {
        long l = System.currentTimeMillis();
        //newVirtualThreadPerTaskExecutor为每个任务创建一个虚拟线程
        try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
            IntStream.range(0, 1000_000).forEach(i -> {
                executor.submit(() -> {
                    try {
                        //睡眠1秒，模拟耗时操作
                        Thread.sleep(Duration.ofNanos(100));
//                        System.out.println("执行任务:" + i);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                });
            });
        }
        System.out.println("耗时2:" + (System.currentTimeMillis() - l));
    }

    private static void oldThread() {
        long l = System.currentTimeMillis();
        //ExecutorService实现了AutoCloseable接口，可以自动关闭了
        try (ExecutorService executor = Executors.newCachedThreadPool()) {
            //向executor中提交1000000个任务
            IntStream.range(0, 1000000).forEach(
                    i -> {
                        executor.submit(() -> {
                            try {
                                //睡眠1秒，模拟耗时操作
                                Thread.sleep(Duration.ofNanos(100));
//                                System.out.println("执行任务:" + i);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                        });
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("耗时1:" + (System.currentTimeMillis() - l));
    }
}
